library(ggplot2)
library(gridExtra)
library(tidyverse)
library(texreg)

# Set paths for figure and table output
figurespath <- "."
tablesspath <- "."

# Load dataset
data <- read_csv("countrylevel.csv")

# Generate three groups of regimes
ctr <- data %>% select(cowcode, v2x_polyarchy) %>% distinct(cowcode, v2x_polyarchy)
ctr$bin <- cut(ctr$v2x_polyarchy, quantile(ctr$v2x_polyarchy, prob = seq(0, 1, length.out = 4), na.rm=T), include.lowest = TRUE, labels=F)
mid <- ctr %>% group_by(bin) %>%  summarize(mid=mean(v2x_polyarchy)) 
ctr <- ctr %>% select(-v2x_polyarchy)
data <- data %>% inner_join(ctr)

# Produce Figure 2 in the main article
p1 <- ggplot(data, aes(y=(num_polisci_institutions/num_institutions), x=v2x_libdem)) + geom_point() + geom_smooth() + theme_bw() + ylab("Share insitutions w/ PS division") +xlab("Electoral democracy") + ylim(-0.1, 1) + geom_text(data = subset(data, cowcode==212), aes(y=(num_polisci_institutions/num_institutions), x=v2x_libdem, label=countrycode), color = "black", nudge_y = -0.05) + geom_text(data = subset(data, cowcode==940), aes(y=(num_polisci_institutions/num_institutions), x=v2x_libdem, label=countrycode), color = "black", nudge_y = -0.05) + geom_text(data = subset(data, cowcode==483), aes(y=(num_polisci_institutions/num_institutions), x=v2x_libdem, label=countrycode), color = "black", nudge_y = -0.05) + geom_text(data = subset(data, cowcode==420), aes(y=(num_polisci_institutions/num_institutions), x=v2x_libdem, label=countrycode), color = "black", nudge_y = -0.05) + geom_text(data = subset(data, cowcode==411), aes(y=(num_polisci_institutions/num_institutions), x=v2x_libdem, label=countrycode), color = "black", nudge_y = -0.05)
ggsave(file.path(figurespath, "sharepoliscicountry.pdf"), p1, height=4, width=6)

# Regression results: determinants of PS share (institutions)
lm1 <- lm(I(num_polisci_institutions/num_institutions) ~  as.factor(bin) + log10(gdp_pc) + log10(population), data=data)
lm2 <- lm(I(num_polisci_divisions/num_divisions) ~ as.factor(bin) + log10(gdp_pc) + log10(population), data=data)

# Create table in Appendix Section A.3
texreg(list(lm1, lm2), file=file.path(tablesspath, "m1_share.tex"), include.ci = FALSE, custom.coef.map=list("as.factor(bin)2" = "Hybrid", "as.factor(bin)3" = "Democratic", "log10(gdp_pc)" = "GDP p.c. (log)", "log10(population)" = "Country pop. (log)", "(Intercept)" = "(Intercept)"), table=F, stars = c(0.001, 0.01, 0.05), digits=3, booktabs = T, use.packages = FALSE)




